import { createRouter, createWebHistory } from 'vue-router'
import Layout from '../layout/index.vue'
import { useUserStore } from '../stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('../views/Home.vue'),
      // component: Layout,
      // redirect: '/home',
      // children: [
      //   {
      //     path: "/home",
      //     name: "Home",
      //     component: () => import('../views/Home.vue'),
      //     meta: {
      //       keepAlive: true
      //     }
      //   },
      //   {
      //     path: "/about",
      //     name: "about",
      //     component: () => import('../views/AboutView.vue'),
      //     meta: {
      //       keepAlive: true
      //     }
      //   },
      // ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
    },
  ],
})

// 白名单路由，不需要登录就可以访问
const whiteList = ['/login']

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const hasToken = userStore.token

  if (hasToken) {
    if (to.path === '/login') {
      // 已登录，访问登录页则重定向到首页
      next({ path: '/' })
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      // 未登录可以访问白名单页面
      next()
    } else {
      // 未登录且访问的不是白名单页面，重定向到登录页
      next(`/login?redirect=${to.path}`)
    }
  }
})

export default router
